﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Infrastructure;
using DormMS.IService;
using DormMS.Model;
using DormMS.Model.ViewModels;
using ServiceStack;
using Senparc.Weixin.MP.Entities.Menu;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin;
using Infrastructure.Pub;
using Infrastructure.Dao;
using SqlSugar;
using NLog;

namespace DormMS.Service
{
    public class WxMenuService : IWxMenuService
    {
        private static Logger NLog = LogManager.GetLogger("Request");
        public MenuDataResponse GetWxMenu()
        {
            using (var Db = DbConfig.GetInstance())
            {
                MenuDataResponse response = new MenuDataResponse();
                response.WxName = PubConst.SiteName;

                List<ParentMenu> parentlist = new List<ParentMenu>();
                List<WxMenu> parentmenu = Db.Queryable<WxMenu>().Where(m => m.ParentId == 0).OrderBy(o => o.Sort).ToList();
                Random ra = new Random();
                if (parentmenu != null && parentmenu.Count > 0)
                {
                    foreach (var item in parentmenu)
                    {
                        var childmenu = Db.Queryable<WxMenu>().Where(m => m.ParentId == item.Id).OrderBy(o => o.Sort).ToList();
                        var childmenulist = new List<ChildMenu>();
                        if (childmenu != null && childmenu.Count > 0)
                        {
                            childmenu.ForEach(m => childmenulist.Add(m.ConvertTo<ChildMenu>()));
                            childmenulist.ForEach(m => m.GUID = Convert.ToInt32(ra.Next(0, 1000000)));
                        }
                        parentlist.Add(new ParentMenu
                        {
                            ChildMenuList = childmenulist,
                            Sort = item.Sort,
                            ParentCustomContent = item.CustomContent,
                            ParentMenuId = item.Id,
                            ParentMenuKey = item.MenuKey,
                            ParentMenuName = item.MenuName,
                            ParentMenuType = item.MenuType,
                            ParentMenuUrl = item.MenuUrl,
                            GUID = Convert.ToInt32(ra.Next(0, 1000000))
                        });
                    }

                }

                response.MenuList = parentlist;
                return response;
            }
        }


        public Result SubmitMenu(List<ParentMenu> MenuList)
        {
            using (var Db = DbConfig.GetInstance())
            {
                MenuList = MenuList ?? new List<ParentMenu>();
                if (MenuList.Count > 0)
                {
                    Regex reg = new Regex("^(?:[\u4e00-\u9fa5|a-zA-Z|0-9])+?$");
                    Regex reg2 = new Regex("^(?:[\u4e00-\u9fa5])+?$");
                    foreach (var parentitem in MenuList)
                    {
                        #region 验证菜单名称
                        if (string.IsNullOrWhiteSpace(parentitem.ParentMenuName))
                        {
                            return Result.Failure("主菜单名称不能为空");
                        }

                        bool isparentmatch = false;
                        if (reg.IsMatch(parentitem.ParentMenuName))
                        {
                            int i = 0;
                            foreach (char item in parentitem.ParentMenuName)
                            {
                                if (reg2.IsMatch(item.ToString()))
                                {
                                    i += 2;
                                }
                                else
                                {
                                    i++;
                                }
                            }
                            if (i <= 8)
                            {
                                isparentmatch = true;
                            }
                        }
                        if (!isparentmatch)
                        {
                            return Result.Failure("菜单名称字数不超过4个汉字或8个字母");
                        }
                        #endregion

                        #region 如果有子菜单验证子菜单，如果没有子菜单验证主菜单链接
                        if (parentitem.ChildMenuList != null && parentitem.ChildMenuList.Count > 0)
                        {
                            foreach (var childitem in parentitem.ChildMenuList)
                            {
                                #region 验证菜单名称
                                if (string.IsNullOrWhiteSpace(childitem.MenuName))
                                {
                                    return Result.Failure("子菜单名称不能为空");
                                }

                                bool ischildmatch = false;
                                if (reg.IsMatch(childitem.MenuName))
                                {
                                    int i = 0;
                                    foreach (char item in childitem.MenuName)
                                    {
                                        if (reg2.IsMatch(item.ToString()))
                                        {
                                            i += 2;
                                        }
                                        else
                                        {
                                            i++;
                                        }
                                    }
                                    if (i <= 16)
                                    {
                                        ischildmatch = true;
                                    }
                                }
                                if (!ischildmatch)
                                {
                                    return Result.Failure("菜单名称字数不超过4个汉字或8个字母");
                                }
                                #endregion

                                #region 验证链接
                                switch (childitem.MenuType)
                                {
                                    case "click":
                                        {
                                            if (childitem.MenuKey.StartsWith("BTN_CUSTOMREPLY"))
                                            {
                                                if (string.IsNullOrWhiteSpace(childitem.CustomContent))
                                                {
                                                    return Result.Failure("自动回复内容不能为空");
                                                }
                                                childitem.MenuKey = "BTN_CUSTOMREPLY-" + childitem.Id;
                                            }
                                            if (childitem.MenuKey.StartsWith("BTN_CUSTOMPIC"))
                                            {
                                                if (string.IsNullOrWhiteSpace(childitem.CustomContent))
                                                {
                                                    return Result.Failure("自动回复图片不能为空");
                                                }
                                                childitem.MenuKey = "BTN_CUSTOMPIC-" + childitem.Id;
                                            }
                                            break;
                                        }
                                    case "view":
                                        {
                                            if (childitem.MenuKey == "0")
                                            {
                                                if (string.IsNullOrWhiteSpace(childitem.MenuUrl))
                                                {
                                                    return Result.Failure("自定义链接不能为空");
                                                }
                                            }
                                            break;
                                        }
                                    default:
                                        return Result.Failure("请选择菜单类型");
                                }
                                #endregion

                            }
                        }
                        else
                        {
                            #region 验证主菜单链接
                            switch (parentitem.ParentMenuType)
                            {
                                case "click":
                                    {
                                        if (parentitem.ParentMenuKey.StartsWith("BTN_CUSTOMREPLY"))
                                        {
                                            if (string.IsNullOrWhiteSpace(parentitem.ParentCustomContent))
                                            {
                                                return Result.Failure("自动回复内容不能为空");
                                            }
                                            parentitem.ParentMenuKey = "BTN_CUSTOMREPLY-" + parentitem.ParentMenuId;
                                        }
                                        if (parentitem.ParentMenuKey.StartsWith("BTN_CUSTOMPIC"))
                                        {
                                            if (string.IsNullOrWhiteSpace(parentitem.ParentCustomContent))
                                            {
                                                return Result.Failure("自动回复图片不能为空");
                                            }
                                            parentitem.ParentMenuKey = "BTN_CUSTOMPIC-" + parentitem.ParentMenuId;
                                        }
                                        break;
                                    }
                                case "view":
                                    {
                                        if (parentitem.ParentMenuKey == "0")
                                        {
                                            if (string.IsNullOrWhiteSpace(parentitem.ParentMenuUrl))
                                            {
                                                return Result.Failure("自定义链接不能为空");
                                            }
                                        }
                                        break;
                                    }
                                default:
                                    return Result.Failure("请选择菜单类型");
                            }
                            #endregion
                        }
                        #endregion

                    }
                }

                //数据更新
                var oldparentmenulist = Db.Queryable<WxMenu>().Where(m => m.ParentId == 0).ToList();
                if (oldparentmenulist != null && oldparentmenulist.Count > 0)
                {
                    foreach (var oldparentitem in oldparentmenulist)
                    {
                        var oldchildmenulist = Db.Queryable<WxMenu>().Where(m => m.ParentId == oldparentitem.Id).ToList();
                        if (!MenuList.Any(m => m.ParentMenuId == oldparentitem.Id))
                        {
                            oldparentitem.IsDeleted = true;
                            Db.Update(oldparentitem);
                        }
                        if (oldchildmenulist != null && oldchildmenulist.Count > 0)
                        {
                            foreach (var oldchilditem in oldchildmenulist)
                            {
                                oldchilditem.IsDeleted = true;
                                Db.Update(oldchilditem);
                            }
                        }
                    }
                }

                if (MenuList.Count > 0)
                {
                    foreach (var parentitem in MenuList)
                    {
                        #region 主菜单信息更新
                        int parentId = 0;
                        if (parentitem.ParentMenuId == 0)
                        {
                            parentId = Db.Insert(new WxMenu
                            {
                                Id = parentitem.ParentMenuId,
                                CustomContent = parentitem.ParentCustomContent,
                                MenuKey = parentitem.ParentMenuKey,
                                MenuName = parentitem.ParentMenuName,
                                MenuType = parentitem.ParentMenuType,
                                MenuUrl = parentitem.ParentMenuUrl,
                                ParentId = 0,
                                Sort = parentitem.Sort
                            }, true).ObjToInt();
                        }
                        else
                        {
                            var parentmodel = Db.Queryable<WxMenu>().SingleOrDefault(m => m.Id == parentitem.ParentMenuId);
                            parentmodel.CustomContent = parentitem.ParentCustomContent;
                            parentmodel.MenuKey = parentitem.ParentMenuKey;
                            parentmodel.MenuName = parentitem.ParentMenuName;
                            parentmodel.MenuType = parentitem.ParentMenuType;
                            parentmodel.MenuUrl = parentitem.ParentMenuUrl;
                            parentmodel.Sort = parentitem.Sort;
                            parentmodel.IsDeleted = false;
                            Db.Update(parentmodel);
                            parentId = parentitem.ParentMenuId;
                        }
                        if (parentitem.ParentMenuKey.StartsWith("BTN_CUSTOMREPLY") && parentId > 0)
                        {
                            var tempparent = Db.Queryable<WxMenu>().SingleOrDefault(m => m.Id == parentId);
                            tempparent.MenuKey = "BTN_CUSTOMREPLY-" + parentId.ToString();
                            Db.Update(tempparent);
                        }
                        if (parentitem.ParentMenuKey.StartsWith("BTN_CUSTOMPIC") && parentId > 0)
                        {
                            var tempparent = Db.Queryable<WxMenu>().SingleOrDefault(m => m.Id == parentId);
                            tempparent.MenuKey = "BTN_CUSTOMPIC-" + parentId.ToString();
                            Db.Update(tempparent);
                        }
                        #endregion

                        #region 子菜单信息更新
                        if (parentitem.ChildMenuList != null && parentitem.ChildMenuList.Count > 0)
                        {
                            foreach (var childitem in parentitem.ChildMenuList)
                            {
                                int childId = 0;
                                if (childitem.Id == 0)
                                {
                                    childId = Db.Insert(new WxMenu
                                    {
                                        Id = childitem.Id,
                                        CustomContent = childitem.CustomContent,
                                        MenuKey = childitem.MenuKey,
                                        MenuName = childitem.MenuName,
                                        MenuType = childitem.MenuType,
                                        MenuUrl = childitem.MenuUrl,
                                        ParentId = parentId,
                                        Sort = childitem.Sort
                                    }, true).ObjToInt();
                                }
                                else
                                {
                                    childitem.IsDeleted = false;
                                    Db.Update(childitem);
                                    childId = childitem.Id;
                                }
                                if (childitem.MenuKey.StartsWith("BTN_CUSTOMREPLY") && childId > 0)
                                {
                                    var tempchild = Db.Queryable<WxMenu>().SingleOrDefault(m => m.Id == childId);
                                    tempchild.MenuKey = "BTN_CUSTOMREPLY-" + childId.ToString();
                                    Db.Update(tempchild);
                                }
                                if (childitem.MenuKey.StartsWith("BTN_CUSTOMPIC") && childId > 0)
                                {
                                    var tempchild = Db.Queryable<WxMenu>().SingleOrDefault(m => m.Id == childId);
                                    tempchild.MenuKey = "BTN_CUSTOMPIC-" + childId.ToString();
                                    Db.Update(tempchild);
                                }
                            }
                        }
                        #endregion
                    }
                }
                return Result.Success();
            }
        }


        public Result GenerateMenu(List<ParentMenu> MenuList)
        {
            try
            {


                var saveresult = SubmitMenu(MenuList);
                if (!saveresult.isSuccess)
                {
                    return saveresult;
                }

                var wxconfig = new WxConfigService().GetConfig();
                if (wxconfig == null || wxconfig.AppId.IsNullOrEmpty())
                {
                    return Result.Failure("未设置AppId");
                }

                using (var Db = DbConfig.GetInstance())
                {
                    //生成菜单
                    ButtonGroup bg = new ButtonGroup();
                    var menulist = Db.Queryable<WxMenu>().Where(m => m.ParentId == 0).ToList();
                    if (menulist != null && menulist.Count > 0)
                    {
                        foreach (var parentitem in menulist.OrderBy(o => o.Sort))
                        {
                            var childmenulist = Db.Queryable<WxMenu>().Where(m => m.ParentId == parentitem.Id).ToList();
                            if (childmenulist != null && childmenulist.Count > 0)
                            {
                                SubButton subButton = new SubButton()
                                {
                                    name = parentitem.MenuName
                                };
                                foreach (var childitem in childmenulist.OrderBy(o => o.Sort))
                                {
                                    switch (childitem.MenuType)
                                    {
                                        case "view":
                                            subButton.sub_button.Add(new SingleViewButton()
                                            {
                                                url = childitem.MenuUrl,
                                                name = childitem.MenuName
                                            });
                                            break;
                                        case "click":
                                            subButton.sub_button.Add(new SingleClickButton()
                                            {
                                                key = childitem.MenuKey,
                                                name = childitem.MenuName
                                            });
                                            break;
                                    }
                                }
                                bg.button.Add(subButton);
                            }
                            else
                            {
                                switch (parentitem.MenuType)
                                {
                                    case "view":
                                        bg.button.Add(new SingleViewButton()
                                        {
                                            name = parentitem.MenuName,
                                            url = parentitem.MenuUrl
                                        });
                                        break;
                                    case "click":
                                        bg.button.Add(new SingleClickButton()
                                        {
                                            name = parentitem.MenuName,
                                            key = parentitem.MenuKey
                                        });
                                        break;
                                }
                            }
                        }
                    }
                    var result = CommonApi.CreateMenu(wxconfig.AppId, bg);
                    if (result.errcode == ReturnCode.请求成功)
                    {
                        return Result.Success();
                    }
                    else
                    {
                        return Result.Failure(result.errmsg);
                    }

                }
            }
            catch (Exception ex)
            {
                NLog.Debug("微信菜单生成异常：" + ex.Message + "，" + ex.StackTrace);
                return Result.Failure("生成异常");
            }
        }

    }
}
